package com.filters;

import com.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//拦截所有页面
@WebFilter(urlPatterns = {"/*"})
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //当程序启动的时候，会调用此方法
        System.out.println("初始化.......init......");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //System.out.println("过滤过程.......doFilter......");
        //当程序访问对应地址时会调用此方法...
        //如何判断这个人是否已经登陆
        //获取这个house的session
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String path = httpServletRequest.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //System.out.println("请求路径是："+httpServletRequest.getServletPath());
        HttpSession session = httpServletRequest.getSession();
        //获取请求路径，不会获取项目路径
        String url = httpServletRequest.getServletPath();
        //获取User
        User user = (User) session.getAttribute("user");

        //获取方法的内容
        String method = request.getParameter("method");
        if (user == null) {
            //没有登陆，只要带login请求都可以通过
            if (!url.startsWith("/catlogin") && !url.startsWith("/static/") && !url.startsWith("/jsp/")
                && !"catlogin".equals(method) && !url.startsWith("/assets/") && !"user".equals(method)) {
                session.setAttribute("msg", "您没有权限访问此页面，请先登录");
                //路径是相对路径,使用绝对路径
                httpServletResponse.sendRedirect(basePath + "catlogin?method=toLoginPage");
                return;
            }
        }

        //放行
        chain.doFilter(request, response);

        //System.out.println("过滤过程.......doFilter......后........");
    }

    @Override
    public void destroy() {
        System.out.println("销毁........destroy.......");
    }
}
